package dfs;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

// TODO: 2021/9/20 待解決
public class leetcode802找到最终的安全状态 {
    private final Set<Integer> circleNode = new HashSet<>();
    public List<Integer> eventualSafeNodes(int[][] graph) {
        List<Integer> list = new ArrayList<>();
        boolean[][] visited = new boolean[graph.length][];
        for (int i = 0; i < graph.length; i++) {
            visited[i] = new boolean[graph[i].length];
        }
        for (int i = 0; i < graph.length; i++) {
            if (!circleNode.contains(i)) {
                fillFalse(visited);
                list.clear();
                list.add(i);
                dfs(list, visited, graph, i);
            }
        }
        list.clear();
        for (int i = 0; i < graph.length; i++) {
            if (!circleNode.contains(i)) {
                list.add(i);
            }
        }
        return list;
    }

    private void fillFalse(boolean[][] visited) {
        int row = visited.length;
        for (int i = 0; i < row; i++) {
            int col = visited[i].length;
            for (int j = 0; j < col; j++) {
                visited[i][j] = false;
            }
        }
    }

    public void dfs(List<Integer> list, boolean[][] visited, int[][] graph, int node) {
        if (graph[node].length == 0) {
            return;
        }
        for (int i = 0; i < graph[node].length; i++) {
            if (list.contains(graph[node][i])) {
                circleNode.addAll(new HashSet<>(list));
            } else {
                visited[node][i] = true;
                list.add(graph[node][i]);
                dfs(list, visited, graph, graph[node][i]);
                list.remove(list.size() - 1);
                visited[node][i] = false;
            }
        }
    }
}
